#!/bin/bash
#
# Routines for locking shared Pulley operations (file should be sourced)
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 11 November 2013
#
#   Copyright 2012-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


## lock_pulley
##
## Tries to acquire the Pulley lock specified in the P_LOCKFILE variable. If
## successful, returns 0. Returns non-zero status if unsuccessful.
##
function lock_pulley() {
	local status=0
	if [ -e "${P_LOCKFILE}" ]; then
		if [ -r "${P_LOCKFILE}" ]; then
			local lockpid=$(cat "${P_LOCKFILE}" 2>/dev/null)
			ps -p ${lockpid} > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				status=21
			else
				rm -f "${P_LOCKFILE}" 2>/dev/null
				if [ $? -ne 0 ]; then
					echo "User does not have lock management permissions"
					status=22
				fi
			fi
		else
			echo "User does not have lock management permissions"
			status=22
		fi
	fi

	if [ ${status} -eq 0 ]; then
		echo $$ > "${P_LOCKFILE}" 2>/dev/null
		if [ $? -ne 0 ]; then
			echo "Could not acquire Pulley lock (permission denied)"
			status=23
		else
			# Test for race condition with 2 running copies of Pulley; not
			# foolproof since filesystem access may not be atomic
			local checkpid=$(cat "${P_LOCKFILE}" 2>/dev/null)
			if [ ${checkpid} -ne $$ ]; then
				echo "Another copy of Pulley is already running (pid ${lockpid})"
				status=21
			fi
		fi
	fi

	return ${status}
}

function unlock_pulley() {
	rm -f "${P_LOCKFILE}" 2>/dev/null
	return $?
}
